import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { ChatMessage, ChatSession, AIQueryRequest } from '@/types'
import { chatAPI, aiAPI } from '@/api'
import { useAuthStore } from './auth'

export const useChatStore = defineStore('chat', () => {
  // State
  const sessions = ref<ChatSession[]>([])
  const currentSession = ref<ChatSession | null>(null)
  const messages = ref<ChatMessage[]>([])
  const context = ref<ChatMessage[]>([])
  const loading = ref(false)
  const typing = ref(false)
  const error = ref<string | null>(null)
  const tokenUsage = ref(0)

  // Getters
  const currentMessages = computed(() => messages.value.filter(
    msg => !currentSession.value?.id || msg.session_id === currentSession.value.id
  ))

  const hasMessages = computed(() => currentMessages.value.length > 0)

  const lastMessage = computed(() => {
    const msgs = currentMessages.value
    return msgs.length > 0 ? msgs[msgs.length - 1] : null
  })

  const isWaitingForResponse = computed(() => {
    const last = lastMessage.value
    return last?.role === 'user' && typing.value
  })

  // Helper functions
  const generateSessionId = (): string => {
    return `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }

  const createSession = (title?: string): ChatSession => {
    const session: ChatSession = {
      id: generateSessionId(),
      title: title || `对话 ${new Date().toLocaleString()}`,
      created_at: new Date(),
      updated_at: new Date(),
      message_count: 0,
      token_usage: 0
    }
    return session
  }

  // Actions
  const startNewSession = async (title?: string) => {
    try {
      // 调用后端API创建新会话
      const response = await chatAPI.createSession({ title })
      if (response.success) {
        const session = response.data
        sessions.value.unshift(session)
        currentSession.value = session
        messages.value = []
        context.value = []
        error.value = null
        
        // 保存到localStorage
        localStorage.setItem('current_session_id', session.id)
        console.log('✅ 新会话创建成功:', session.title)
      }
    } catch (err: any) {
      console.error('❌ 创建会话失败:', err)
      // 降级处理：使用本地创建
      const session = createSession(title)
      sessions.value.unshift(session)
      currentSession.value = session
      messages.value = []
      context.value = []
      error.value = null
    }
  }

  const switchSession = async (sessionId: string) => {
    const session = sessions.value.find(s => s.id === sessionId)
    if (!session) return

    currentSession.value = session
    error.value = null
    
    // Save current session to localStorage for persistence
    localStorage.setItem('current_session_id', sessionId)
    console.log('💾 保存当前会话ID:', sessionId)
    
    // Load messages for this session
    await loadSessionMessages(sessionId)
  }

  const loadSessionMessages = async (sessionId: string, loadMore = false) => {
    loading.value = true
    try {
      const limit = 20
      const offset = loadMore ? messages.value.length : 0
      
      const response = await chatAPI.getHistory({ 
        session_id: sessionId, 
        limit, 
        offset 
      })
      
      if (response.success) {
        const newMessages = response.data.map(msg => ({
          ...msg,
          timestamp: new Date(msg.timestamp || Date.now())
        }))
        
        if (loadMore) {
          // 向上滚动加载更多历史消息，插入到数组开头
          // 由于后端按DESC排序返回，我们需要反转顺序插入到前面
          messages.value = [...newMessages.reverse(), ...messages.value]
        } else {
          // 初次加载，由于后端返回的是DESC顺序，需要反转为正确的时间顺序
          messages.value = newMessages.reverse()
        }
        
        // Build context from recent messages (最新的10条)
        context.value = messages.value.slice(-10)
        
        return newMessages.length // 返回加载的消息数量
      }
    } catch (err: any) {
      error.value = err.response?.data?.message || '加载对话历史失败'
    } finally {
      loading.value = false
    }
    return 0
  }

  const sendMessage = async (content: string) => {
    if (!content.trim() || loading.value) return

    const authStore = useAuthStore()
    if (!authStore.isAuthenticated) {
      error.value = '请先登录'
      return
    }

    // Create user message
    const userMessage: ChatMessage = {
      role: 'user',
      content: content.trim(),
      timestamp: new Date(),
      session_id: currentSession.value?.id
    }

    // Add to messages immediately for UI responsiveness
    messages.value.push(userMessage)

    // Create session if none exists
    if (!currentSession.value) {
      startNewSession()
      userMessage.session_id = currentSession.value!.id
    }

    // Update context
    context.value = [...context.value, userMessage].slice(-10)

    loading.value = true
    typing.value = true
    error.value = null

    try {
      // Save user message to backend
      await chatAPI.saveMessage({
        message: userMessage.content,
        role: userMessage.role,
        session_id: userMessage.session_id,
        token_usage: 0 // 用户消息不消耗token
      })

      // Prepare AI request
      const aiRequest: AIQueryRequest = {
        message: content,
        context: context.value.map(msg => ({
          role: msg.role,
          content: msg.content,
          timestamp: msg.timestamp
        })),
        session_id: currentSession.value?.id
      }

      // Send to AI
      const aiResponse = await aiAPI.chat(aiRequest)

      if (aiResponse.success) {
        let assistantMessage: ChatMessage
        
        // 根据AI返回的数据类型创建不同的消息
        if (aiResponse.data.type === 'table') {
          assistantMessage = {
            role: 'assistant',
            content: aiResponse.data.summary || `已查询${aiResponse.data.data?.title || '数据表'}`,
            timestamp: new Date(),
            session_id: currentSession.value?.id,
            // 添加结构化数据
            data: aiResponse.data.data,
            messageType: 'table',
            // 如果有SQL语句，也保存下来
            sqlStatements: aiResponse.data.sqlStatements
          }
        } else if (aiResponse.data.type === 'action_result') {
          assistantMessage = {
            role: 'assistant',
            content: aiResponse.data.data?.message || '操作完成',
            timestamp: new Date(),
            session_id: currentSession.value?.id,
            data: aiResponse.data.data,
            messageType: 'action'
          }
        } else if (aiResponse.data.type === 'sql') {
          // SQL消息类型 - 包含SQL语句
          assistantMessage = {
            role: 'assistant',
            content: aiResponse.data.message || 'AI生成了SQL语句',
            timestamp: new Date(),
            session_id: currentSession.value?.id,
            sqlStatements: aiResponse.data.sqlStatements, // 保存SQL语句数组
            messageType: 'sql'
          }
        } else {
          // 普通文本消息
          assistantMessage = {
            role: 'assistant',
            content: aiResponse.data.message || aiResponse.data.summary || 'AI回复异常',
            timestamp: new Date(),
            session_id: currentSession.value?.id,
            messageType: 'text'
          }
        }
        
        // Add to messages
        messages.value.push(assistantMessage)

        // Update context with AI response
        context.value = aiResponse.data.context || [...context.value, assistantMessage].slice(-10)

        // Update token usage
        if (aiResponse.data.usage?.total_tokens) {
          tokenUsage.value += aiResponse.data.usage.total_tokens
          if (currentSession.value) {
            currentSession.value.token_usage += aiResponse.data.usage.total_tokens
          }
        }

        // Save assistant message to backend with metadata
        await chatAPI.saveMessage({
          message: assistantMessage.content,
          role: assistantMessage.role,
          session_id: assistantMessage.session_id,
          token_usage: aiResponse.data.usage?.total_tokens || 0,
          metadata: {
            messageType: assistantMessage.messageType,
            data: assistantMessage.data
          }
        })

        // Update session info
        if (currentSession.value) {
          currentSession.value.message_count = messages.value.filter(
            msg => msg.session_id === currentSession.value?.id
          ).length
          currentSession.value.updated_at = new Date()
        }

      } else {
        throw new Error(aiResponse.message || 'AI服务响应异常')
      }

    } catch (err: any) {
      console.error('发送消息失败:', err)
      error.value = err.response?.data?.message || err.message || '发送消息失败，请重试'
      
      // Remove the user message if AI failed
      messages.value = messages.value.filter(msg => msg !== userMessage)
    } finally {
      loading.value = false
      typing.value = false
    }
  }

  const loadMoreMessages = async () => {
    if (!currentSession.value || loading.value) return false
    
    const loadedCount = await loadSessionMessages(currentSession.value.id, true)
    return loadedCount > 0
  }

  const retryLastMessage = async () => {
    const lastUserMessage = [...messages.value].reverse().find(msg => msg.role === 'user')
    if (lastUserMessage) {
      // Remove any assistant messages after the last user message
      const lastUserIndex = messages.value.lastIndexOf(lastUserMessage)
      messages.value = messages.value.slice(0, lastUserIndex + 1)
      
      // Resend
      await sendMessage(lastUserMessage.content)
    }
  }

  const deleteMessage = async (messageIndex: number) => {
    if (messageIndex >= 0 && messageIndex < messages.value.length) {
      messages.value.splice(messageIndex, 1)
      
      // Update context
      context.value = messages.value.slice(-10)
      
      // Update session message count
      if (currentSession.value) {
        currentSession.value.message_count = messages.value.filter(
          msg => msg.session_id === currentSession.value?.id
        ).length
      }
    }
  }

  const clearCurrentSession = async () => {
    if (!currentSession.value) return

    try {
      await chatAPI.clearHistory(currentSession.value.id)
      messages.value = []
      context.value = []
      
      if (currentSession.value) {
        currentSession.value.message_count = 0
        currentSession.value.token_usage = 0
      }
    } catch (err: any) {
      error.value = err.response?.data?.message || '清除对话失败'
    }
  }

  const deleteSession = async (sessionId: string) => {
    try {
      // 调用后端API删除会话
      await chatAPI.deleteSession(sessionId)
      
      // Remove from sessions
      sessions.value = sessions.value.filter(s => s.id !== sessionId)
      
      // If current session was deleted, start new one
      if (currentSession.value?.id === sessionId) {
        currentSession.value = null
        messages.value = []
        context.value = []
        localStorage.removeItem('current_session_id')
        
        // 如果还有其他会话，切换到最新的
        if (sessions.value.length > 0) {
          await switchSession(sessions.value[0].id)
        } else {
          // 没有会话了，创建新的
          await startNewSession('新对话')
        }
      }
      
      console.log('✅ 会话删除成功:', sessionId)
    } catch (err: any) {
      console.error('❌ 删除会话失败:', err)
      error.value = err.response?.data?.message || '删除会话失败'
    }
  }

  const loadSessions = async () => {
    try {
      const response = await chatAPI.getSessions()
      if (response.success && response.data) {
        sessions.value = response.data.map(session => ({
          ...session,
          created_at: new Date(session.created_at),
          updated_at: new Date(session.updated_at)
        }))
      }
    } catch (err: any) {
      error.value = err.response?.data?.message || '加载会话列表失败'
    }
  }

  const updateSessionTitle = (sessionId: string, title: string) => {
    const session = sessions.value.find(s => s.id === sessionId)
    if (session) {
      session.title = title
      session.updated_at = new Date()
    }
  }

  // Smart query functions
  const queryBusinessData = async (query: string, type?: 'auto' | 'product' | 'customer' | 'order') => {
    loading.value = true
    try {
      const response = await aiAPI.query({ query, type })
      if (response.success) {
        return response.data
      } else {
        throw new Error(response.message)
      }
    } catch (err: any) {
      error.value = err.response?.data?.message || '数据查询失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  const getBusinessAnalysis = async (type: 'sales' | 'inventory' | 'customer' | 'all', dateRange?: { start: string; end: string }) => {
    loading.value = true
    try {
      const response = await aiAPI.analyze({ type, dateRange })
      if (response.code === 200) {
        return response.data
      } else {
        throw new Error(response.message)
      }
    } catch (err: any) {
      error.value = err.response?.data?.message || '业务分析失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  const getAISuggestions = async (context?: string, data?: any) => {
    loading.value = true
    try {
      const response = await aiAPI.suggest({ context, data })
      if (response.success) {
        return response.data
      } else {
        throw new Error(response.message)
      }
    } catch (err: any) {
      error.value = err.response?.data?.message || '获取AI建议失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  const clearError = () => {
    error.value = null
  }

  // Initialize store
  const initialize = async () => {
    try {
      console.log('🔄 初始化聊天存储...')
      await loadSessions()
      
      // Try to restore last session from localStorage
      const lastSessionId = localStorage.getItem('current_session_id')
      let sessionFound = false
      
      if (lastSessionId && lastSessionId !== 'undefined' && lastSessionId !== 'null' && sessions.value.length > 0) {
        const lastSession = sessions.value.find(s => s.id === lastSessionId)
        if (lastSession) {
          console.log('📂 恢复上次会话:', lastSession.title)
          await switchSession(lastSession.id)
          sessionFound = true
        } else {
          console.log('🧹 清理无效的会话ID')
          localStorage.removeItem('current_session_id')
        }
      }
      
      // If no current session or last session not found, use most recent or create new
      if (!sessionFound) {
        if (sessions.value.length === 0) {
          console.log('🆕 创建新会话')
          startNewSession('欢迎使用 X-Synergy OS')
        } else {
          console.log('📂 切换到最近会话')
          const recentSession = sessions.value[0]
          await switchSession(recentSession.id)
        }
      }
      
      console.log('✅ 聊天存储初始化完成')
    } catch (error) {
      console.error('❌ 聊天存储初始化失败:', error)
      // Fallback: create new session
      startNewSession('欢迎使用 X-Synergy OS')
    }
  }

  return {
    // State
    sessions,
    currentSession,
    messages,
    context,
    loading,
    typing,
    error,
    tokenUsage,
    
    // Getters
    currentMessages,
    hasMessages,
    lastMessage,
    isWaitingForResponse,
    
    // Actions
    startNewSession,
    switchSession,
    loadSessionMessages,
    loadMoreMessages,
    sendMessage,
    retryLastMessage,
    deleteMessage,
    clearCurrentSession,
    deleteSession,
    loadSessions,
    updateSessionTitle,
    
    // Smart queries
    queryBusinessData,
    getBusinessAnalysis,
    getAISuggestions,
    
    // Utilities
    clearError,
    initialize
  }
})
